#!/usr/bin/perl
#!/opt/oss/perl5/bin/perl
# vi:ts=4:sw=4

BEGIN {
	push @::INC,"libs";
}
	
use MIME::Base64;
use Data::Dumper;
use CGI;
use CGI::Session;
use gri_frontend;
# use gri_conversions;
use gri_roles_config;
use gri_userprefs;

my $gri_roles = new gri_roles_config("gri_roles_config.xml");

# W
my $cgi = new CGI;
my $session = new CGI::Session("driver:File", $cgi, {Directory=>'/tmp'});
# print STDERR Dumper($session);
my $params=$cgi->Vars;
# print STDERR "push_file params:",Dumper($params);
my $logged_in_as=$session->param("NAME");
# print STDERR "logged_in_as: $logged_in_as\n";
$::GRI_FRONTEND=gri_frontend->new("globals_config.xml");
if(!defined($::GRI_FRONTEND)) {
	print $cgi->header("text/plain");
	print "Unable to defined gri_header!\n";
	exit(0);
}
my $attempted_login_as=undef;
$login_cookie=undef;
my $auto_login=$::GRI_FRONTEND->get_auto_login();
if(!defined($logged_in_as) || !length($logged_in_as)) {
	print STDERR "Attempt auto-login...\n";
	if(defined($auto_login)) {
		print STDERR "Auto login as '$auto_login'\n";
		$attempted_login_as=$auto_login;
		$session->param("NAME",$auto_login);
		$session->flush();
		# Also set login cookie...
		$login_cookie=$cgi->cookie(-name=> "login", -value => $auto_login);
		# Get/set the preferences cookie..
		my $users_dir=$::GRI_FRONTEND->get_global_directory("users");
		my $xx;
		if(-f "$users_dir/$auto_login-prefs.xml") {
			print STDERR "Loading User preferences.\n";
			$xx=new gri_userprefs("$users_dir/$auto_login-prefs.xml");
			if(! $xx) {
				my $e=gri_userprefs::get_error();
				print STDERR "Cannot load prefernces: $e\n";
			}
		} elsif(-f "$users_dir/__DEFAULT__-prefs.xml") {
			print STDERR "Loading Default preferences.\n";
			$xx=new gri_userprefs("$users_dir/__DEFAULT__-prefs.xml");
			if(! $xx) {
				my $e=gri_userprefs::get_error();
				print STDERR "Cannot load default prefernces: $e\n";
			}
		} else {
			print STDERR "No preferences available.\n";
		}
		if(defined($xx)) {
			my @P=$xx->get_pref_list();
			my %vals=();
			for my $cp (@P) {
				$vals{$cp}=$xx->get_pref_value($cp);
			}
			$prefs_cookie = $cgi->cookie(-name=> "GRI2_prefs", -value => \%vals);
		} else {
			print STDERR "User has no prefs ... and no defaults available. [$users_dir/__DEFAULT__-prefs.xml]\n";
		}
		# my $l="$::ENV{HTTP_HOST}$::ENV{SCRIPT_NAME}";
		# if($::ENV{SERVER_PORT}==80) {
			# $l="http://$l";
		# } else {
			# $l="https://$l";
		# }
		# my $hh=$cgi->redirect(-uri=>$l,-nph=>1);
		# print STDERR  "hh=$hh\n";
		# print "Location: $l\n\n";
	} else {
		print STDERR "Auto login Failed. :(\n";
	}
}

my $cookie = $cgi->cookie(CGISESSID => $session->id);
my @cl=($cookie);
if(defined($prefs_cookie)) {
	push @cl,$prefs_cookie;
}
if(defined($login_cookie)) {
	push @cl,$login_cookie;
}
# The dl= deeplink is for showing a portal, report list or report instance.
# We deal with that via a param and set a cookie for the JS to use.
# If we have a deeplink add to cookie list and reload without it?
if(exists($params->{dl})) {
	my $cookie2 = $cgi->cookie(GRI2DL => $params->{dl});
	push @cl,$cookie2;
		my $l="$::ENV{HTTP_HOST}$::ENV{SCRIPT_NAME}";
		if($::ENV{SERVER_PORT}==80) {
			$l="http://$l";
		} else {
			$l="https://$l";
		}
		# my $hh=$cgi->redirect(-uri=>$l,-nph=>1,-status => 302, -cookie => [@cl]);
		# my $hh=$cgi->redirect(-uri=>$l,-nph=>1,-cookie => [@cl]);
		# my $hh=$cgi->redirect(-uri=>$l,-nph=>1);
		my @CC=();
		for my $_cookie (@cl) {
			push @CC,"Set-Cookie: $_cookie";
		}
		$hh=join("\n",@CC) . "\nLocation: $l\n\n";
		print STDERR  "hh=$hh\n";
		print $hh;
		exit(0);
}

# Similarly there are other possible command line parameters that
# should be dealt with. This lists any defined:
#
# 1. sd=alerts - show the alerts dialogue once logged in.
# 2. sd=prefs  - show the preferences dialogue once logged in.

if(exists($params->{sd})) {
	my $cookie2 = $cgi->cookie(GRI2SD => $params->{sd});
	push @cl,$cookie2;
		my $l="$::ENV{HTTP_HOST}$::ENV{SCRIPT_NAME}";
		if($::ENV{SERVER_PORT}==80) {
			$l="http://$l";
		} else {
			$l="https://$l";
		}
		# my $hh=$cgi->redirect(-uri=>$l,-nph=>1,-status => 302, -cookie => [@cl]);
		# my $hh=$cgi->redirect(-uri=>$l,-nph=>1,-cookie => [@cl]);
		# my $hh=$cgi->redirect(-uri=>$l,-nph=>1);
		my @CC=();
		for my $_cookie (@cl) {
			push @CC,"Set-Cookie: $_cookie";
		}
		$hh=join("\n",@CC) . "\nLocation: $l\n\n";
		print $hh;
		exit(0);
}

print $cgi->header(-type => 'text/html',-cookie => [@cl]);
# print $cgi->header("text/html");
# and read in/parse _index.html.
my $url_prefix=$::GRI_FRONTEND->get_url_prefix();
my $extjs4_url_prefix=$::GRI_FRONTEND->get_extjs4_url_prefix();
my $title=$::GRI_FRONTEND->get_variable("TITLE");
my @VL=$::GRI_FRONTEND->get_variable_list();
my @VV=();
for my $cv (@VL) {
	push @VV,"var griglobs_$cv=\"" . $::GRI_FRONTEND->get_variable($cv) . "\";";
}
if(defined($auto_login) && $::GRI_FRONTEND->allow_logout()==0) {
	push @VV,"var griglobs_ALLOW_LOGOUT=0;";
}
if(defined($gri_roles)) {
	push @VV,"var griroles_titles = new Array();";
	push @VV,"var griroles_descs = new Array();";
	my @RL=$gri_roles->get_role_list();
	for my $cr (@RL) {
		my @X=$gri_roles->get_role_details($cr);
		if(@X) {
			push @VV,"griroles_titles[\"$cr\"]=\"$X[0]\";";
			push @VV,"griroles_descs[\"$cr\"]=\"$X[1]\";";
		}
	}
}
print "
<html>
<head>
	<title>$title</title>
	<link rel=\"stylesheet\" type=\"text/css\" href=\"$extjs4_url_prefix/resources/css/ext-all.css\">
	<link rel=\"stylesheet\" type=\"text/css\" href=\"$url_prefix/resources/css/gri2.css\">
</head>
<body>
<body>
    <script>
";
print join("\n",@VV);
if(defined($attempted_login_as)) {
	print "var griglobs_ATTEMPTED_LOGIN_AS=\"$attempted_login_as\";\n";
}
print "
    </script>
	<script type=\"text/javascript\" src=\"$extjs4_url_prefix/ext-all-debug.js\"></script>
	<script type=\"text/javascript\" src=\"direct_api.js\"></script>
	<script type=\"text/javascript\" src=\"sprintf-0.6.js\"></script>
	<script type=\"text/javascript\" src=\"base64.js\"></script>
	<script type=\"text/javascript\" src=\"app.js\"></script>
</body>
</html>
";
